import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { rmSync } from 'node:fs'
import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus';
import viteCompression from 'vite-plugin-compression';
// import { buildConfig } from './src/utils/build';
import electron from "vite-plugin-electron";
import legacy from '@vitejs/plugin-legacy'
import renderer from "vite-plugin-electron-renderer";
import requireTransform from "vite-plugin-require-transform";
import vueJsx from '@vitejs/plugin-vue-jsx'

const pathResolve = (dir: string) => resolve(__dirname, '.', dir);

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
	rmSync('dist-electron', { recursive: true, force: true })
	// console.log("🚀 ~ viteConfig ~ mode:", mode)
	const env = loadEnv(mode.mode, process.cwd());
	// const isBuild = mode.command === 'build';
	return {
		plugins: [
			vue(),
			// vueJsx(),
			vueSetupExtend(),
			// viteCompression(),
			// JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.cdn() : null,
			requireTransform({
				fileRegex: /.ts$|.tsx$|.vue$/,
				// fileRegex:/.js$|.jsx$|.vue$/
			}),
			// legacy({
			// 	targets: ['defaults', 'ie >= 11', 'chrome 52'],  //需要兼容的目标列表，可以设置多个
			// 	additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
			// 	renderLegacyChunks: true,
			// 	polyfills: [
			// 		'es.symbol',
			// 		'es.array.filter',
			// 		'es.promise',
			// 		'es.promise.finally',
			// 		'es/map',
			// 		'es/set',
			// 		'es.array.for-each',
			// 		'es.object.define-properties',
			// 		'es.object.define-property',
			// 		'es.object.get-own-property-descriptor',
			// 		'es.object.get-own-property-descriptors',
			// 		'es.object.keys',
			// 		'es.object.to-string',
			// 		'web.dom-collections.for-each',
			// 		'esnext.global-this',
			// 		'esnext.string.match-all'
			// 	]
			// }),
			electron([
				{
					// Main-Process entry file of the Electron App.
					entry: "electron/main.ts",
					vite: {
						build: {
							rollupOptions: {
								plugins: [
								],
							},
						},
					},
				},
				{
					entry: "electron/preload.ts",
					onstart(options) {
						// Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete,
						// instead of restarting the entire Electron App.
						options.startup();
					},
				},
			]),
			renderer(),
		],
		// root: process.cwd(),
		resolve: { alias },
		// base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		base: mode.command === 'serve' ? '' : './',
		// base: './',
		// optimizeDeps: { exclude: ['vue-demi'] },
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT as unknown as number,
			open: JSON.parse(env.VITE_OPEN),
			// hmr: true,
			hmr: {
				overlay: false
			},
			proxy: {
				'/gitee': {
					target: 'https://gitee.com',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/gitee/, ''),
				},
				'/gesong': {
					target: 'http://uk.frp.one:49156/',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/gesong/, ''),
				}
			},
		},
		build: {
			emptyOutDir: false, // 默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录
			outDir: 'dist',
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)?.groups!.moduleName ?? 'vender';
						}
					},
				},
				// ...(JSON.parse(env.VITE_OPEN_CDN) ? { external: buildConfig.external } : {}),
			},
		},
		css: {
			preprocessorOptions: {
				// css: {
				// 	charset: false
				// },
				scss: {
					api: 'modern-compiler'
				}
			}
		},
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
			APP_VERSION: JSON.stringify(process.env.npm_package_version),
		},
	};
});

export default viteConfig;
